from django.shortcuts import render

# Create your views here.
from cmdb.settings import base
from scanhost.models import Server


def get_active_hosts(hosts='192.168.43.100', ports='22,80'):
    pass


def is_ssh_up(host='192.168.43.100', port=22, timeout=5):
    pass


def login_ssh_key(host, port, user, keyfile, command):
    pass


def scanhost(request):
    # 访问所有要扫描的网段/IP
    for host in base.scanhosts:
        print("正在扫描%s......" % (host))
        # 获取所有可以ping通的主机IP
        active_hosts = get_active_hosts(hosts=host)
        # 一次遍历判断ssh服务是否开启
        for active_host in active_hosts:
            if is_ssh_up(active_host):
                server = Server()
                # 设置IP地址
                server.IP = active_host
                # 执行指令
                for attr, command in base.commands.items():
                    # attr ='hostname' , command = 'hostname'
                    # 存储主机名、操作系统.....指令执行的结果
                    result = login_ssh_key(active_host, 22, 'root', '/mnt/id_rsa', command)
                    setattr(server, attr, result)
                server.save()
        return HttpResponse('扫描成功')
